package app.models.brand;

import com.github.sog.annotation.TableBind;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * The table ol_brand_attention mapping model.
 * </p>
 */
@TableBind(tableName = "ol_brand_attention")
public class BrandAttention extends Model<BrandAttention> {

    private static final long   serialVersionUID = 1L;
    /**
     * The public dao.
     */
    public static final BrandAttention dao = new BrandAttention();


    public BrandAttention findByMemberAndBrand(long mid, long brandid) {
        return findFirst(SqlKit.sql("brandattention.findByMemberAndBrand"), mid, brandid);
    }

    public int onOrUnAttention(long brandid, long mid, String wxno) {
        long count = Db.queryLong(SqlKit.sql("brandattention.attentioncount"), brandid, mid);
        if (count != 0) {
            unAttention(brandid, mid, wxno);
            return -1;
        } else {
            onAttention(brandid, mid, wxno);
            return 1;
        }
    }

    private void unAttention(long brandid, long mid, String wxno) {
        Db.update(SqlKit.sql("brandattention.unattention"), brandid, mid);
    }

    public void onAttention(long brandid, long mid, String wxno) {
        BrandAttention ba = new BrandAttention();
        ba.set("brand", brandid);
        ba.set("attention_time", new Date());
        ba.set("member", mid);
        ba.set("wx_account", wxno);
        ba.set("create_time", new Date());
        ba.save();
    }

    /**
     * 查询所有关注信息
     * @param mid 会员id
     */
    public List<BrandAttention> findByMemberId(int mid) {
        return dao.find(SqlKit.sql("brandattention.findByMemberId"),mid);
    }
}
